package com.junit;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hcfly.utils.ESClient;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.Test;

import java.io.IOException;
import java.util.Map;

public class TermTermsQueryDemo {
    ObjectMapper mapper = new ObjectMapper();
    RestHighLevelClient client =  ESClient.getClient();
    String index = "sms_logs_index";
    String type="sms_logs_type";

    @Test
    public void termsQuery() throws IOException {
        SearchRequest request = new SearchRequest(index);
        request.types(type);

        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.query(QueryBuilders.termsQuery("province.keyword", "石河子", "天水"));
        request.source(builder);

        SearchResponse resp = client.search(request, RequestOptions.DEFAULT);
        for (SearchHit hit : resp.getHits().getHits()) {
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            System.out.println(sourceAsMap.toString());
        }
    }

    @Test
    public void termQuery() throws IOException {
        /**
         * term查询，完全匹配
         */
        // 1,新建request对象
        SearchRequest request = new SearchRequest(index);
        request.types(type);

        //2， 指定查询条件
        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.from(0);
        builder.size(5);
        builder.query(QueryBuilders.termQuery("province.keyword", "北京"));
        request.source(builder);

        //3,执行查询
        SearchResponse res = client.search(request, RequestOptions.DEFAULT);

        // 4.查询结果
        for (SearchHit hit : res.getHits().getHits()) {
            Map<String, Object> result = hit.getSourceAsMap();
            System.out.println(result.toString());

        }


    }
}
